#include "YGif.h"
#include "gif.h"

#include <QUuid>
#include <QDir>
#include <QFileInfo>
#include <QBuffer>
#include <QImage>

#define pGifWriter reinterpret_cast<Gif::GifWriter*>(gifWriter)

#include "MediaCommon.h"

YGif::YGif(QObject* parent): YMedia(parent), gif(new Gif)
{

}

YGif::~YGif()
{
    if(isOpen()){
        close();
    }
    delete gif;
}

bool YGif::open()
{
    setTempFileName();

    close();
    Gif::GifWriter* t_gifWriter = new Gif::GifWriter;
    gifWriter = reinterpret_cast<quintptr>(t_gifWriter);

    return true;
}

void YGif::setVideo(int width, int height, double fps, const QString &)
{
    frameWidth = static_cast<uint32_t>(width);
    frameHeight = static_cast<uint32_t>(height);
    frameFps = static_cast<uint32_t>(fps);

    char* cFileName = MediaCommon::QStringToChars(tempFileName);
    isOpened = gif->GifBegin(pGifWriter, cFileName, frameWidth, frameHeight, frameFps);
    delete [] cFileName;
    if(!isOpened){
        close();
        tempFileName.clear();
        return;
    }
}

void YGif::addFrame(const QImage &frame)
{
    QImage image = frame.convertToFormat(QImage::Format_RGBA8888);
    gif->GifWriteFrame(pGifWriter, image.bits(), frameWidth, frameHeight, frameFps);
}

int YGif::close()
{
    if(isOpen()){
        isOpened = false;
        gif->GifEnd(pGifWriter);
        delete pGifWriter;
        return 1;
    }
    return 0;
}

bool YGif::save(const QString &outputFileName)
{
    if(tempFileName.isEmpty()) return false;
    if(isOpen()){
        close();
    }

    bool ret = QFile(tempFileName).copy(outputFileName);
    QFile::remove(tempFileName);
    return ret;
}

QString YGif::saveFileType()
{
    return "GIF动态图片(*.gif)";
}

#include <QFileDialog>
QString YGif::defaultFileDialog()
{
    return QFileDialog::getSaveFileName(nullptr, "保存", "未命名.gif", "GIF动态图片(*.gif)");
}
